<template>
  <el-container>
    <el-header>
      <el-button @click="$router.push('/')">返回首页</el-button>
    </el-header>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <h2>留言板</h2>
            <MessageForm @refresh="getMessages" />
            <el-table :data="messages" style="width: 100%">
              <el-table-column prop="name" label="访客名称" width="120" />
              <el-table-column prop="content" label="留言内容" />
              <el-table-column
                prop="create_time"
                label="留言时间"
                width="180"
              />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteMessage(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="8">
          <Sidebar />
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Sidebar from '../components/Sidebar.vue'
import MessageForm from '../components/MessageForm.vue'
import api from '../api'

const messages = ref([])

const getMessages = async () => {
  const res = await api.get('/messages')
  messages.value = res.data.result
}

const deleteMessage = async (id) => {
  await api.delete(`/messages/${id}`)
  getMessages()
}

onMounted(getMessages)
</script>
